package com.ndood.polling.domain.polling.v1.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.ndood.api.base.constaints.ApiCode;
import com.ndood.api.base.dao.record_receive.v1.ExtendRecoRecPayDao;
import com.ndood.api.base.exception.ApiException;
import com.ndood.api.domain.record.receive.v1.entity.dto.RecoRecPayDto;
import com.ndood.common.base.constaints.CommonConstaints;
import com.ndood.polling.app.task.PollingParam;
import com.ndood.polling.base.constaints.PollingConstaints;
import com.ndood.polling.domain.receive.v1.service.RecPlatformOfflineOfficialAlif2fService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class PollingService {

	@Autowired
	private ExtendRecoRecPayDao extendRecoRecPayDao;
	
	@Autowired
	private RecPlatformOfflineOfficialAlif2fService recPlatformOfflineOfficialAlif2fService;

	/**
	 * 1 分发轮询渠道
	 */
	public void distributePolling(PollingParam param) {
		try {
			// Step1: 根据渠道订单号查询出渠道订单
			String payOrderNo = param.getPayOrderNo();
			Assert.notNull(payOrderNo, "收款渠道订单不能为空！");

			RecoRecPayDto payOrder = extendRecoRecPayDao.extendFindReceivePayByPayOrderNo(payOrderNo);
			Assert.notNull(payOrder, "收款渠道订单不存在！");

			// Step2: 创建中的订单才需要轮询
			if (!CommonConstaints.REC_CHANNEL_PAY_STATUS_CREATE.equals(payOrder.getStatus())) {
				throw new ApiException(ApiCode.ERR_SERVER, "不支持的收款渠道订单状态");
			}

			// Step3: 查询 or 撤销
			if(PollingConstaints.POLLING_QUERY.equals(param.getFlag())) {
				doWithQuery(payOrder, param);
			}
			if(PollingConstaints.POLLING_CANCEL.equals(param.getFlag())) {
				doWithCancel(payOrder, param);
			}

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	private void doWithQuery(RecoRecPayDto payOrder, PollingParam param) throws ApiException {
		
		if(CommonConstaints.CN_GF_ALI_BAR.equals(payOrder.getChannelNo())) {
			recPlatformOfflineOfficialAlif2fService.queryBar(payOrder, param);
		}
		
		throw new ApiException(ApiCode.ERR_SERVER, "不支持的收款渠道类型");
		
	}
	
	private void doWithCancel(RecoRecPayDto payOrder, PollingParam param) throws ApiException {
		
		if(CommonConstaints.CN_GF_ALI_BAR.equals(payOrder.getChannelNo())) {
			recPlatformOfflineOfficialAlif2fService.cancelBar(payOrder, param);
		}
		
		throw new ApiException(ApiCode.ERR_SERVER, "不支持的收款渠道类型");
	}

}
